package xxl.robotlegs.framework.impl 
{
	import flash.utils.Dictionary;
	import xxl.robotlegs.utils.CallBackUtil;
	/**
	 * ...
	 * @author XXL
	 */
	public class MessageDispatcher 
	{
		private const _handlers:Dictionary = new Dictionary();
		
		public function MessageDispatcher() 
		{
			
		}
		
		public function addMessageHandler(message:Object, handler:Function):void
		{
			const messageHandlers:Array = _handlers[message];
			if (messageHandlers)
			{
				if (messageHandlers.indexOf(handler) == -1)
				{
					messageHandlers.push(handler);
				}
			}
			else
			{
				_handlers[message] = [handler];
			}
		}
		
		public function hasMessageHandler(message:Object):Boolean
		{
			return _handlers[message];
		}
		
		public function removeMessageHandler(message:Object, handler:Function):void
		{
			const messageHandlers:Array = _handlers[message];
			const index:int = messageHandlers?messageHandlers.indexOf(handler): -1;
			if (index != -1)
			{
				messageHandlers.splice(index, 1);
				if (messageHandlers.length == 0)
				{
					delete _handlers[message];
				}
			}
		}
		
		public function dispatchMessage(message:Object, callback:Function, reverse:Boolean = false):void
		{
			var handlers:Array = _handlers[message];
			if (handlers)
			{
				handlers = handlers.concat();
				reverse || handlers.reverse();
				new MessageRunner(message, handlers, callback).run();
			}
			else
			{
				callback && CallBackUtil.SafelyCallBack(callback, null, null);
			}
		}
		
	}

}
import xxl.robotlegs.utils.CallBackUtil;
import xxl.signals.base.events.GenericEvent;

class MessageRunner
{
	private var _message:Object;
	private var _handlers:Array;
	private var _callback:Function;
	
	public function MessageRunner(message:Object, handlers:Array, callback:Function)
	{
		_message = message;
		_handlers = handlers;
		_callback = callback;
	}
	
	public function run():void
	{
		next();
	}
	
	private function next():void
	{
		for (var handler:Function = _handlers.pop(); handler; )
		{
			if (handler.length == 0)
			{
				handler();
			}
			else if (handler.length == 1)
			{
				handler(new GenericEvent());
			}
			else if (handler.length == 2)
			{
				handler(new GenericEvent(), _message);
			}
			else if (handler.length == 3)
			{
				trace("bad");
				//var handled:Boolean;
				//handler(_message, function(error:Object = null, msg:Object = null):void
				//{
					//if (handled)
					//{
						//return;
					//}
					//handled = true;
					//if (error || _handlers.length == 0)
					//{
						//_callback && CallBackUtil.SafelyCallBack(_callback, error, _message);
					//}
					//else
					//{
						//next();
					//}
				//}
				//);
				return;
			}
			else
			{
				throw new Error("无法处理的handler");
			}
			handler = _handlers.pop();
		}
		_callback && CallBackUtil.SafelyCallBack(_callback, null, _message);
	}
}